package com.vandzi.android.androidcode.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.util.Log;

import com.vandzi.android.androidcode.model.Application;
import com.vandzi.android.androidcode.model.ApplicationDetails;

public class AndroidCodeService {

	private static final String TAG = "AndroidCodeService";

	/**
	 * Parse applications from web
	 * 
	 * @return applicationsList
	 */
	public static ArrayList<Application> parseApplications() {

		ArrayList<Application> applications = new ArrayList<Application>();

		try {

			Document doc = Jsoup.connect("http://www.androidcode.sk/aplikacie")
					.get();

			Elements elemets = doc.select("div[id^=post]");
			int order = 0;
			for (Element element : elemets) {
				try {
					String name = element.select(
							"div[class=entry nothumb] h2[class=title] a")
							.text();
					String author = element.select("div.author span").text();
					String linkToImage = element.select("div[class=thumb] img")
							.attr("src");
					String linktToDetail = element.select(
							"div[class=entry nothumb] h2[class=title] a").attr(
							"href");

					String score = element.select(
							"div[class=entry nothumb] span[data-type=score]")
							.text();

					String averageRating = element.select(
							"div[class=entry nothumb] span[data-type=average]")
							.text();

					String marketLink = element
							.select("div[class=entry nothumb] span[data-type=market_link]")
							.text();

					Application app = new Application(name, author,
							linkToImage, linktToDetail, averageRating,
							marketLink, score, order++);

					applications.add(app);
				} catch (Exception e) {
					// If some problem, ignore app
				}
			}

		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
		}

		return applications;

	}

	/**
	 * Parse details about application
	 * 
	 * @param application
	 * @return
	 */
	public static Application parseApplicationDetails(Application application) {

		try {

			Connection connection = Jsoup.connect(application
					.getLinktToDetail());

			Document doc = connection.get();

			Element elemet = doc.select(
					"div[class=app-detail] div[class=entry]").first();

			Element description = elemet.select("div[class=description]")
					.first();

			Element aggregate = description.select(
					"span[class=hreview-aggregate]").first();
			String rating = "0";
			String votes = "0";
			if (aggregate != null) {

				Element averageEl = aggregate.select("span.average").first();

				if (averageEl != null) {
					rating = averageEl.text();
				}
				Element countEl = aggregate.select("span.count").first();

				if (countEl != null) {
					votes = countEl.text();
				}

				aggregate.remove();
			}

			String descriptionInHtml = description.html();
			ApplicationDetails details = new ApplicationDetails(
					descriptionInHtml, votes, rating);

			application.setApplicationDetails(details);

		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
		}

		return application;

	}

	public static void login(String login, String password) {

		try {
			HttpClient client = new DefaultHttpClient();
			String postURL = "http://www.androidcode.sk/prihlasenie";
			HttpPost post = new HttpPost(postURL);
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("log", ""));
			params.add(new BasicNameValuePair("pwd", ""));
			UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,
					HTTP.UTF_8);
			post.setEntity(ent);
			HttpResponse responsePOST = client.execute(post);
			HttpEntity resEntity = responsePOST.getEntity();

			if (resEntity != null) {
				Log.i("RESPONSE", EntityUtils.toString(resEntity));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
